const fs = require("fs")
const sysPath = require("path")
const templates = fs.readdirSync(sysPath.resolve(__dirname, "../../packages"))
  .filter(template => template.indexOf("plugin") > -1)
//移出老版本的目录
let vueTemplates = templates.filter((template) => (template.indexOf("vue") > -1 && template.indexOf("old") == -1))
let reactTemplates = templates.filter((template) => (template.indexOf("vue") == -1 && template.indexOf("svelte") == -1 && template.indexOf("old") == -1))
let vueRectified = [
  "analyzer-vue-plugin",
  "app-vue-plugin",
  "bigscreen-vue-plugin",
  "canvas-vue-plugin",
  "reporting-vue-plugin"
]
let reactReactified = [
  "analyzer-plugin",
  "app-plugin",
  "bigscreen-plugin",
  "canvas-plugin",
  "app-top-custom-plugin",
  "data-form-list-plugin",
  "data-form-list-query-plugin",
  "detail-custom-btn-plugin",
  "list-custom-btn-plugin",
  "reporting-plugin",
  "custom-process-node-plugin"
]
// reactTemplates = reactReactified
// vueTemplates = vueRectified
let updateBlackList = ["reporting-plugin/src/utils/handlePlatform/UseDelegator.js"]
updateBlackList = updateBlackList.map((item) => {
  return sysPath.normalize(item)
})
copy("templates")
copy("vue templates", "vue")
copy("react templates", "react")

async function copy(src, type) {
  // 读取目录中的所有文件/目录
  if ((src === "react templates" || src === "templates" || src === "vue templates") && !fs.existsSync(sysPath.resolve(__dirname, src))) {
    return
  }
  let paths = fs.readdirSync(sysPath.join(__dirname, src))
  for (let i = 0; i < paths.length; i++) {
    let _src = sysPath.normalize(src + "/" + paths[i])
    let fileStat = await stat(sysPath.join(__dirname, _src))
    // 判断是否为文件
    if (fileStat.isFile()) {
      let tempPath = _src.split(sysPath.sep)
      tempPath.shift()
      tempPath = tempPath.join(sysPath.sep)
      let packages = type === undefined ? templates : type === "vue" ? vueTemplates : reactTemplates
      packages.forEach((packageName) => {
        let targetPath = sysPath.resolve(__dirname, `../../packages/${packageName}/${tempPath}`)
        copyFileForTarget(targetPath, tempPath, _src, packageName)
      })
      if (type == undefined) {
        ["vue", "react"].forEach((item) => {
          let targetPath = sysPath.resolve(__dirname, `../../templates/${item}/${tempPath}`)
          copyFileForTarget(targetPath, tempPath, _src)
        })
      } else {
        let targetPath = sysPath.resolve(__dirname, `../../templates/${type}/${tempPath}`)
        copyFileForTarget(targetPath, tempPath, _src)
      }
    }
    // 如果是目录则递归调用自身
    else if (fileStat.isDirectory()) {
      await copy(_src, type)
    }
  }
}

function copyFileForTarget(targetPath, tempPath, _src, packageName) {
  let targetDir = targetPath.split(sysPath.sep)
  targetDir.pop()
  targetDir = targetDir.join(sysPath.sep)
  let dirIsExist = fs.existsSync(targetDir)
  if (!dirIsExist) {
    mkdirSync(targetDir)
  }
  if (packageName && updateBlackList.includes(sysPath.normalize(`${packageName}/${tempPath}`))) {
    console.log("此文件不执行更新操作")
    return
  }
  fs.copyFile(sysPath.resolve(__dirname, _src), targetPath, (err) => {
    if (err) {
      throw new Error(`复制出错，目录为${_src}，目标目录${targetPath}`)
    }
    console.log("success")
  })
}

//封装stat为promise
async function stat(path) {
  return new Promise((resolve, reject) => {
    fs.stat(path, function (err, data) {
      if (err) {
        reject(err)
      }
      resolve(data)
    })
  })
}

function mkdirSync(dirname) {
  if (fs.existsSync(dirname)) {
    return true
  } else {
    //如果父级目录已经创建，然后才能创建子级目录
    if (mkdirSync(sysPath.dirname(dirname))) {
      fs.mkdirSync(dirname)
      return true
    }
  }
}
